<?php
namespace app\admin\middleware;

use app\admin\logic\user\Token as UserToken;
use app\common\exception\UnauthorizedException;
use Closure;

class BindLoginUser
{
    public function handle($request, Closure $next)
    {
        $request->admin_user_id = 0;
        $request->user          = false;
        // 如果引用了路由登录排除中间件,则不进行登录检查
        if ($request->needLogin === false) {
            return $next($request);
        }

        // 进行登录验证
        $ak = $request->header('E-USER-AK', '');
        $sk = $request->header('E-USER-SK', '');
        if (!$ak || !$sk) {
            throw new UnauthorizedException(null, 402);
        }

        // 获取用户
        $user = app(UserToken::class)->getUserWithToken($ak, $sk);
        if ($user === false) {
            throw new UnauthorizedException(null, 402);
        }

        $request->user = $user;
        // 权限验证
        // $node = $request->rule()->getName();
        // 格式验证
        // if (preg_match('/^[\d\.\w]+$/', $node)) {
        //     // 符合节点命名,进行节点权限验证
        // }

        $request->admin_user_id = $user->id ?? 0;
        $request->is_platform   = config('eduline.appinfo.mhm', false) && $user->mhm_id === 1;
        $request->mhm_id        = $user->mhm_id;// 定义为后端路由

        return $next($request);
    }

}
